<template>
    <div class="production-material-order">
        <!-- 操作按钮区 -->
        <div class="action-buttons">
            <el-button @click="Save" type="primary">保存</el-button>
            <el-button @click="hoshow">取消</el-button>
            <el-button type="success">审核</el-button>
            <el-button type="info">反审核</el-button>
            <el-button @click="toggleFormVisibility">{{ isFormVisible ? '收起' : '展开' }}</el-button>
        </div>

        <!-- 表单信息区 -->
        <el-form v-if="isFormVisible" :model="formInfo" label-width="100px" style="margin-bottom: 20px;">
            <el-row :gutter="20">
                <el-col :span="4">
                    <el-form-item label="单据编码">
                        <el-input v-model="formInfo.documentCode" disabled />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="业务类型">
                        <el-select v-model="formInfo.businessType" placeholder="请选择" readonly>
                            <el-option label="装配车间" value="装配车间" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="仓库">
                        <el-select v-model="formInfo.warehouse" placeholder="请选择" readonly>
                            <el-option label="零部件仓" value="零部件仓" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="物料编码">
                        <el-input v-model="formInfo.materialCode" disabled />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="批次领料">
                        <el-input v-model="formInfo.batchMaterial" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="4">
                    <el-form-item label="单据日期">
                        <el-date-picker v-model="formInfo.documentDate" type="date" readonly value="2025-04-25" />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="操作员">
                        <el-input v-model="formInfo.operator" disabled readonly value="njrsun" />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="跟单编号">
                        <el-input v-model="formInfo.followNumber" disabled />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="物料名称">
                        <el-input v-model="formInfo.materialName" disabled />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="备注">
                        <el-input v-model="formInfo.remark" type="textarea" style="height: auto;" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="4">
                    <el-form-item label="单据状态">
                        <el-tag type="warning" v-model="formInfo.danjun" disabled>开立</el-tag>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="审核员">
                        <el-input v-model="formInfo.auditor" disabled />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="生产单号">
                        <div style="display: flex; align-items: center;">
                            <el-input v-model="formInfo.productionNumber" disabled placeholder="选择"
                                style="flex: 1; margin-right: 10px;" />
                            <el-button size="small" @click="showProductionOrderDialog">选择</el-button>
                        </div>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="计量单位">
                        <el-input v-model="formInfo.unit" disabled />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="4">
                    <el-form-item label="业务状态">
                        <el-select v-model="formInfo.businessStatus" placeholder="请选择" readonly>
                            <el-option label="正常" value="正常" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="审核日期">
                        <el-date-picker v-model="formInfo.auditDate" type="date" disabled />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="生产线">
                        <el-input v-model="formInfo.productionLine" disabled />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="订单数量">
                        <el-input v-model="formInfo.orderQuantity" disabled />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <!-- 物料信息表格 -->
        <div class="material-info">
            <el-button type="primary" size="small" style="float: right; margin-bottom: 5px;"
                @click="Yinru()">引入</el-button>
            <el-table :data="materialList" border style="width: 100%;">
                <el-table-column type="index" label="序号" width="50" />
                <el-table-column label="MBOM单据" prop="boMid" width="140" />
                <el-table-column label="物料编码" prop="boMdateid" width="140" />
                <el-table-column label="物料名称" prop="boMname" width="140" />
                <el-table-column label="型号规格" prop="boMunit" width="120" />
                <el-table-column label="主计量" prop="bomNumer" width="80" />
                <el-table-column label="领用数量" prop="bomQuantity" width="100" />
                <el-table-column label="出库数量" prop="bomQuantityclaimed" width="100" />
                <el-table-column label="备注" prop="bomQremark" width="120" />
                <el-table-column label="操作" width="80">
                    <template #default="{ row }">
                        <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 生产订单选择对话框 -->
        <el-dialog v-model="productionOrderDialogVisible" title="选择生产订单" width="80%" destroy-on-close>
            <div class="order-search" style="display: flex; align-items: center; flex-wrap: wrap; margin-bottom: 10px;">
                <el-input placeholder="跟单编号" v-model="searchParams.followNumber" style="flex: 1; margin-right: 10px;" />
                <el-input placeholder="物料编码" v-model="searchParams.materialCode" style="flex: 1; margin-right: 10px;" />
                <el-input placeholder="物料名称" v-model="searchParams.materialName" style="flex: 1; margin-right: 10px;" />
                <div style="display: flex; align-items: center; margin-right: 10px;">
                    <el-date-picker v-model="searchParams.startDate" type="date" placeholder="开始日期"
                        style="margin-right: 10px;" />
                    <el-date-picker v-model="searchParams.endDate" type="date" placeholder="结束日期" />
                </div>
                <el-button type="primary" @click="searchProductionOrders">搜索</el-button>
                <el-button @click="queryAllOrders" style="margin-left: 10px;">查询所有</el-button>
            </div>
            <el-table :data="productionOrders" border style="width: 100%;" @row-click="handleRowClick">
                <el-table-column label="跟单编号" prop="tu_status" />
                <el-table-column label="生产订单号" prop="id" />
                <el-table-column label="物料编码" prop="material_code" />
                <el-table-column label="物料名称" prop="name" />
                <el-table-column label="主计量" prop="unit" />
                <el-table-column label="生产数量" prop="production_qty" />
                <el-table-column label="生产日期" prop="production_date" />
                <el-table-column label="选择" width="80">
                    <template #default="{ row }">
                        <el-radio v-model="selectedProductionOrder" :label="row.id"
                            @change="handleRadioChange(row)"></el-radio>
                    </template>
                </el-table-column>
            </el-table>
            <div class="dialog-footer" style="text-align: right; margin-top: 10px;">
                <el-button @click="productionOrderDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmProductionOrder"
                    :disabled="!selectedProductionOrder">确定</el-button>
            </div>
        </el-dialog>

        <!-- 物料清单明细对话框 -->
        <el-dialog v-model="materialImportDialogVisible" title="物料清单明细" width="80%" destroy-on-close>
            <div style="margin-bottom: 10px; text-align: right;">
                <el-button type="primary" size="small" style="margin-right: 5px;">全部物料</el-button>
                <el-button size="small">全选</el-button>
            </div>
            <el-table :data="importMaterialList" border style="width: 100%;">
                <el-table-column label="物料清单" prop="boMid" width="140" />
                <el-table-column label="类型" prop="boMtyoe" width="80" />
                <el-table-column label="物料编码" prop="boMdateid" width="140" />
                <el-table-column label="物料名称" prop="boMname" width="140" />
                <el-table-column label="计量单位" prop="boMunit" width="80" />
                <el-table-column label="物料数量" prop="bomNumer" width="100" />
                <el-table-column label="已领数量" prop="bomQuantity" width="100" />
                <el-table-column label="可领数量" prop="bomQuantityclaimed" width="100" />
                <el-table-column label="备注" prop="bomQremark" width="120" />
                <el-table-column label="操作" width="80">
                    <template #default="{ row }">
                        <el-checkbox v-model="row.checked" />
                    </template>
                </el-table-column>
            </el-table>
            <div style="display: flex; justify-content: space-between; align-items: center; padding: 10px;">
                <div>共 {{ totalItems }} 条</div>
                <div>
                    <el-pagination @size-change="(size) => { currentPage.value = 1; Yinru(); }" @current-change="Yinru"
                        :current-page="currentPage" :page-sizes="[100]" :page-size="100"
                        layout="total, sizes, prev, pager, next, jumper" :total="totalItems" />
                </div>
            </div>
            <div class="dialog-footer" style="text-align: right; margin-top: 10px;">
                <el-button @click="materialImportDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmMaterialImport">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import { useRouter } from 'vue-router';
import { useCounterStore } from "@/stores/counter";
import { KongaUrl } from '@/axios/axiosHelp'
const Store = useCounterStore()
const router = useRouter();

// 表单数据
const formInfo = ref({
    documentCode: '',
    businessType: '装配车间',
    warehouse: '零部件仓',
    materialCode: '',
    batchMaterial: '',
    documentDate: '2025-04-25',
    operator: Store.user.userName,
    followNumber: '',
    materialName: '',
    remark: '',
    auditor: '',
    productionNumber: '',
    unit: '',
    businessStatus: '正常',
    auditDate: '',
    productionLine: '',
    orderQuantity: '',
    danjun: '开立'
});

// 物料表格数据
const materialList = ref([]);

// 表单显示状态
const isFormVisible = ref(true);
const toggleFormVisibility = () => isFormVisible.value = !isFormVisible.value;
const hoshow = () => router.push("/Productionpicking");

// 生产订单对话框状态及数据
const productionOrderDialogVisible = ref(false);
const selectedProductionOrder = ref(null);
const searchParams = ref({
    followNumber: '',
    materialCode: '',
    materialName: '',
    startDate: '',
    endDate: '',
    PageIdex: 1,
    PageSize: 15
});
const productionOrders = ref([]);

// 引入物料对话框状态及数据
const materialImportDialogVisible = ref(false);
const importMaterialList = ref([]);
const currentPage = ref(1);
const totalItems = ref(0);

// 处理生产订单行点击事件
const handleRowClick = (row) => {
    selectedProductionOrder.value = row.id;
};

// 处理生产订单单选按钮变化
const handleRadioChange = (row) => {
    selectedProductionOrder.value = row.id;
};

// 显示生产订单对话框时加载订单
const showProductionOrderDialog = async () => {
    productionOrderDialogVisible.value = true;
    try {
        const response = await KongaUrl.get("/shengchandu/api/Production/Production_orderFile", {
            params: searchParams.value
        });

        productionOrders.value = response.data.data.list || [];
        await nextTick();
    } catch (error) {
        console.error('获取订单数据出错：', error);
        ElMessage.error('获取生产订单失败');
    }
};

// 搜索生产订单
const searchProductionOrders = async () => {
    searchParams.value.PageIdex = 1;
    try {
        const response = await KongaUrl.get("/shengchandu/api/Production/Production_orderFile", {
            params: searchParams.value
        });
        productionOrders.value = response.data.data.list || [];
        await nextTick();
    } catch (error) {
        console.error('搜索订单数据出错：', error);
        ElMessage.error('搜索生产订单失败');
    }

};

// 查询所有生产订单
const queryAllOrders = () => {
    searchParams.value = {
        followNumber: '',
        materialCode: '',
        materialName: '',
        startDate: '',
        endDate: '',
        PageIdex: 1,
        PageSize: 15
    };
    searchProductionOrders();
};

// 确定选择生产订单
const confirmProductionOrder = () => {
    if (selectedProductionOrder.value) {
        const selectedOrder = productionOrders.value.find(
            order => order.id === selectedProductionOrder.value
        );
        axios.get(`https://localhost:7006/api/Production/Production_orderQuser?Id=${selectedOrder.id}`).then((res) => {
            console.log(res.data.data[0].tu_status)
            formInfo.value.followNumber = res.data.data[0].tu_status;
            formInfo.value.productionNumber = res.data.data[0].id;
            formInfo.value.productionLine = res.data.data[0].production_line;
            formInfo.value.materialCode = res.data.data[0].material_code;
            formInfo.value.materialName = res.data.data[0].name;
            formInfo.value.unit = res.data.data[0].unit;
            formInfo.value.orderQuantity = res.data.data[0].production_qty;
            formInfo.value.auditor = "无";
            formInfo.value.auditDate = new Date();
            productionOrderDialogVisible.value = false;
        });
    } else {
        ElMessage.warning('请选择一条生产订单');
    }
};

// 引入物料操作
const Yinru = async () => {
    materialImportDialogVisible.value = true;
    try {
        const response = await KongaUrl.get("/shengchandu/api/Production/BOMdetailsShow");
        const processedData = response.data.data.map(item => ({
            ...item,
            checked: false
        }));
        importMaterialList.value = processedData;
        totalItems.value = response.data.data.length;
    } catch (error) {
        console.error('获取物料清单失败', error);
        ElMessage.error('获取物料清单失败');
    }
};

// 确定引入物料
const confirmMaterialImport = () => {
    const selectedItems = importMaterialList.value.filter(row => row.checked);
    if (selectedItems.length === 0) {
        ElMessage.warning('请选择要引入的物料');
        return;
    }
    QuserShow(selectedItems);
    materialImportDialogVisible.value = false;
};

// 循环逐个查询物料
const QuserShow = async (selectedItems) => {
    const results = [];
    for (const item of selectedItems) {
        try {
            const res = await KongaUrl.get("/shengchandu/api/Production/BOMdetailsQl", {
                params: { BOMid: item.boMid }
            });
            if (res.data && res.data.data && Array.isArray(res.data.data)) {
                results.push(...res.data.data);
            }
        } catch (error) {
            console.error(`查询物料 ${item.boMid} 失败:`, error);
            ElMessage.error(`物料 ${item.boMid} 查询失败，请检查网络或重试`);
        }
    }
    materialList.value = results;
};

// 删除物料清单
const handleDelete = (row) => {
    ElMessageBox.confirm(
        '确定要删除该物料清单吗？',
        '提示',
        { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
    ).then(() => {
        materialList.value = materialList.value.filter(item => item.boMid !== row.boMid);
        ElMessage.success('删除成功');
    }).catch(() => ElMessage.info('已取消删除'));
};


//保存
const Save = () => {
    // 从 formInfo 和 materialList 中正确获取数据
    const {
        documentCode,
        followNumber,
        productionNumber,
        warehouse,
        documentDate,
        danjun,
        operator,
        auditor,
        businessType,
        remark,
        materialCode,
        batchMaterial,
        materialName,
        unit,
        businessStatus,
        auditDate,
        productionLine,
        orderQuantity
    } = formInfo.value;

    // 处理物料清单（假设需要物料列表中的 boMid，这里示例取第一个，实际可能需要遍历）
    const proNameId = materialList.value.length > 0 ? materialList.value[0].boMid : ''; // 按需调整

    const from = {
        // 表单基础信息（修正变量名匹配）
        production_Material_Id: documentCode, // 单据编码
        production_Material_BatchNumber: followNumber, // 跟单编号
        production_Material_ProductionOrderId: productionNumber, // 生产订单号（从表单获取）
        production_Material_Warehouse: warehouse, // 仓库
        production_Material_DocumentDate: documentDate, // 单据日期
        production_Material_Status: danjun, // 单据状态
        production_Material_Operator: operator, // 操作员
        production_Material_Auditor: auditor || '无', // 审核员
        production_Material_BusinessType: businessType, // 业务类型
        production_Material_Remarks: remark, // 备注

        // 物料相关信息（修正变量名和数据来源）
        productionWUId: materialCode, // 物料编码（formInfo.materialCode）
        materialPici: batchMaterial, // 批次领料（formInfo.batchMaterial，修正变量名）
        productionWUName: materialName, // 物料名称
        producMaterialPiciName: unit, // 主计量（formInfo.unit，修正变量名）
        producMaterialSate: businessStatus, // 业务状态
        producMaterTime: auditDate, // 审核日期
        proXian: productionLine, // 生产线
        proNumber: orderQuantity, // 订单数量
        proNameId: proNameId, // 物料清单 ID（从 materialList 中正确获取）
    };

    console.log('保存数据：', from);
    // const from = {
    //     production_Material_Id: formInfo.value.documentCode,
    //     production_Material_BatchNumber: formInfo.value.followNumber,
    //     production_Material_ProductionOrderId: importMaterialList.value.boMid,
    //     production_Material_Warehouse: formInfo.value.warehouse,
    //     production_Material_DocumentDate: formInfo.value.documentDate,
    //     production_Material_Status: formInfo.value.danjun,
    //     production_Material_Operator: formInfo.value.operator,
    //     production_Material_Auditor: formInfo.value.auditor || '无',
    //     production_Material_BusinessType: formInfo.value.businessType,
    //     production_Material_Remarks: formInfo.value.remark,
    //     productionWUId: formInfo.materialCode,
    //     materialPici: formInfo.batchMaterial,
    //     productionWUName: formInfo.materialName,
    //     producMaterialPiciName: formInfo.unit,
    //     producMaterialSate: formInfo.businessStatus,
    //     producMaterTime: formInfo.auditDate,
    //     proXian: formInfo.productionLine,
    //     proNumber: formInfo.orderQuantity,
    //     proNameId: materialList.value.boMid,
    // }
    // console.log(from)
    axios.post("https://localhost:7207/api/Production/Production_MaterialAdd", from).then((res => {
        if (res.data.code == 212) {
            ElMessage({
                message: '添加成功',
                type: 'success',
            })
            router.push("/Productionpicking")
        }
        else {
            ElMessage.error('添加失败')
        }
    }))
}


</script>

<style scoped>
.production-material-order {
    padding: 15px;
}

.action-buttons {
    margin-bottom: 15px;
}

.action-buttons el-button {
    margin-right: 10px;
}

.el-form-item__label {
    font-weight: normal;
    text-align: right;
    padding-right: 10px;
}

.el-input,
.el-select {
    width: 100%;
}

.material-info {
    clear: both;
    margin-top: 15px;
}

.el-table th {
    text-align: center;
}

.el-table td {
    text-align: center;
}

.dialog-footer {
    padding: 10px;
    text-align: right;
}

.dialog-footer el-button {
    margin-left: 10px;
}

.el-radio {
    margin-right: 0;
}
</style>